import {
	USER_TOKEN,REFRESH_TOKEN
} from '@/constants/local-storage-key-const';
import {
	manner
} from "@/util/manner.js"
import store from '@/store/index.js'
// import { decryptData, encryptData } from './encrypt';
// import { useUserStore } from '@/store/modules/system/user';
// let baseUrl = 'http://192.168.2.10:8080/couple'
let baseUrl = "https://da.yueyangtech.com.cn/couple"
// let baseUrl = 'http://192.168.2.2:8080/couple'
// let baseUrl = "https://da.yueyangtech.com.cn/couple"

// #ifndef H5
// baseUrl = "http://111.229.28.25:8080/couple"
// #endif
// #ifdef H5
baseUrl = '/api'
// #endif

function getUserToken() {
	let token = uni.getStorageSync(USER_TOKEN);
	if (token) {
		return token;
	}
	return '';
}
let cachedIpAddress = null;

function getIpAddress() {
	// 如果已经有缓存的IP，直接返回
	if (cachedIpAddress) {
		return Promise.resolve(cachedIpAddress);
	}
	// 首次获取IP
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'http://ip-api.com/json/',
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200) {
					cachedIpAddress = res.data.query; // 缓存IP地址
					resolve(cachedIpAddress);
				} else {
					reject(new Error('Failed to get IP address'));
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
}

/**
 * 通用请求封装
 */
export const request = function(url, method, data, toast) {
	return new Promise((resolve, reject) => {
		getIpAddress().then((ip) => {
			uni.request({
				url: baseUrl + url,
				data: data,
				method: method,
				header: {
					'Authorization': getUserToken(),
					'X-Real-IP': ip // 将IP地址添加到请求头
				},
				success: (response) => {
					console.log('response',response)
					if (response.statusCode == 200) {
						const res = response.data;
						if (res.state && res.state !== 200) {
							if (res.state === 200000) {
								let token = uni.getStorageSync(REFRESH_TOKEN);
								if (token) {
									store.dispatch('refreshToken', {
										token: token
									});
								}else {
									store.commit("logOut")
									uni.redirectTo({
										url: '/pagesMain/mplogin/mplogin'
									})
								}
							}
							if (toast) {
								uni.showToast({
									title: res.msg,
									icon: 'none',
								});
							}
							reject(res);
						} else {
							resolve(res.data);
						}
					} else {
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						})
						reject()
					}

				},
				fail: (error) => {
					reject(error);
				},
			});
		}).catch((error) => {
			console.error('Error getting IP address:', error);
			reject(error);
		});
	});
};

export const OtherRequest = function(url, method, data, toast) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: data,
			method: method,
			success: (response) => {
				if (response.statusCode == 200) {
					const res = response;
					if (res.state && res.state !== 200) {
						if (toast) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							});
						}
						reject(res);
					} else {
						resolve(res);
					}
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
					reject()
				}
			},
			fail: (error) => {
				reject(error);
			},
		});
	});
};

export const AddContTypePostRequest = function(url, method, data, toast = true, config) {
	return new Promise((resolve, reject) => {
		var Header = {
			'Authorization': getUserToken(),
			'Content-Type': 'application/json'
		};
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: Object.assign(Header, config),
			success: (response) => {
				if (response.statusCode == 200) {
					const res = response.data
					if (res.state && res.state !== 200) {
						if (toast) {
							uni.showToast({
								title: res.msg,
								icon: 'none',
							});
						}
						reject(res);
					} else {
						resolve(res.data);
					}
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
					reject()
				}
			},
			fail: (error) => {
				console.log(error, 'error')
				reject(error);
			},
		});
	});
};

export const getRequest = (url, data, toast = true) => {
	return request(url, 'GET', data, toast);
};

export const OtherGetRequest = (url, data, toast = true) => {
	return OtherRequest(url, 'GET', data, toast);
};

export const postRequest = (url, data, toast = true) => {
	return request(url, 'POST', data, toast);
};

export const putRequest = (url, data, toast = true) => {
	return request(url, 'PUT', data, toast);
};

export const putRequest3 = (url, data, toast = true) => {
	return request_2(url, 'PUT', data, toast);
};

export const deleteRequest = (url, data, toast = true) => {
	return request(url, 'DELETE', data, toast);
};
export const deleteRequest2 = (url, params, toast = true) => {
	const queryString = Object.keys(params)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');
	const fullUrl = `${url}?${queryString}`;

	return request(fullUrl, 'DELETE', {}, toast);
};



export const putRequest2 = (url, params, toast = true) => {
	// 将params对象转换为查询字符串
	const queryString = Object.keys(params)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');
	// 将查询字符串添加到URL中
	const fullUrl = `${url}?${queryString}`;
	return request(fullUrl, 'PUT', {}, toast);
};

export const postRequest2 = (url, params, toast = true) => {
	// 将params对象转换为查询字符串
	const queryString = Object.keys(params)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');
	// 将查询字符串添加到URL中
	const fullUrl = `${url}?${queryString}`;
	return request(fullUrl, 'POST', {}, toast);
};

export const DelettRequest2 = (url, params, toast = true) => {
	// 将params对象转换为查询字符串
	const queryString = Object.keys(params)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&');

	// 将查询字符串添加到URL中
	const fullUrl = `${url}?${queryString}`;

	return request(fullUrl, 'DELETE', {}, toast);

};

/**
 * 加密请求参数的post请求
 */
export const postEncryptRequest = (url, data) => {
	return request(url, 'POST', {
		encryptData: encryptData(data)
	});
};

export const uploadRequest = function(filePath, folder) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + '/common/front/common/upload/img',
			filePath,
			header: {
				'token': getUserToken(),
			},
			name: 'file',
			formData: folder,
			success: (response) => {
				if (response.statusCode == 200) {
					const res = JSON.parse(response.data.replace('\uFEFF', ''));
					if (res.code && res.code !== 200) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
						reject(response.data);
					} else {
						resolve(res);
					}
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
					reject()
				}
			},
			fail: (error) => {
				reject(error);
			},
		});
	});
};

export const uploadImage = function(url, parms) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseUrl + url,
			filePath: parms,
			header: {
				'Authorization': getUserToken(),
			},
			name: 'file',
			success: (response) => {
				if (response.statusCode == 200) {
					const res = JSON.parse(response.data.replace('\uFEFF', ''));
					if (res.code && res.code !== 200) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
						reject(response.data);
					} else {
						resolve(res);
					}
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
					reject()
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
};

export const request_2 = function(url, method, data, toast) {
	return new Promise((resolve, reject) => {
		getIpAddress().then((ip) => {
			uni.request({
				url: baseUrl + url,
				data: data,
				method: method,
				header: {
					'Authorization': getUserToken(),
					'X-Real-IP': ip // 将IP地址添加到请求头
				},
				success: (response) => {
					if (response.statusCode == 200) {
						const res = response.data;
						if (res.state && res.state !== 200) {
							if (res.state === 200000) {
								store.commit("logOut")
								uni.redirectTo({
									url: '/pagesMain/mplogin/mplogin'
								})
								return
							}
							if (toast) {
								uni.showToast({
									title: res.msg,
									icon: 'none',
								});
							}
							reject(res);
						} else {
							resolve(res);
						}
					} else {
						uni.showToast({
							title: '网络异常',
							icon: 'none'
						})
						reject()
					}
				},
				fail: (error) => {
					reject(error);
				},
			});
		}).catch((error) => {
			console.error('Error getting IP address:', error);
			reject(error);
		});
	});
};